import json
import csv
import codecs


class nestJson_Csv():

    # 初始化方法，创建csv文件。
    def __init__(self):
        self.save_csv = open('../Json/12345.csv', 'w', encoding='utf-8', newline='')
        self.write_csv = csv.writer(self.save_csv, delimiter=',')  # 以，为分隔符

    def trans(self, filename):
        with codecs.open(filename, 'r', encoding='utf-8') as f:
            self.write_csv.writerow(['id','time','ip','vip','rcip'])
            read = f.readlines()
            flag = True
            for index, info in enumerate(read):
                data = json.loads(info)
                if index < 900000:  # 读取json文件的前90万行写入csv文件 。要是想写入全部，则去掉判断。
                    if flag:  # 截断第一行当做head
                        id_value = data['id']#  获取id
                        time_value = data['time']#  获取time
                        ip_value = data['clientInfo']['ip']#  获取clientInfo中的ip
                        vip_value = data['clientInfo']['vip']#  获取clientInfo中的vip
                        rcip_value = data['rcip']#  获取rcip
                        value = [id_value, time_value, ip_value, vip_value, rcip_value]
                        self.write_csv.writerow(value)
            self.save_csv.close()  # 写完就关闭


if __name__=='__main__':
    json_csv=nestJson_Csv()
    path='../Json/vpnlog.json'
    json_csv.trans(path)